﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using Website.Logger;
using System.Drawing;
using DAL;
using BOL;
using WebLib;
using System.Web.Script.Services;
using System.Web.Services;
using UtilityExtensions;
namespace UILGestion.Control
{
    public partial class ECItemDetallarPanel : System.Web.UI.UserControl
    {
       

        public List<EstructuraCostoitemsingleInfo> ItemLista
        { 
            get {
                return (List<EstructuraCostoitemsingleInfo>)Session[idRecursoPartirList.Value.ToString()];
        } }

        public int idestructuraCostoitem
        {
            get
            {
                return int.Parse(idEstructuraCostoPartir.Value);
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!this.IsPostBack)
                {
                    idEstructuraCosto.Value = (string)Request.QueryString["id"];
                    FormatForm();

                }
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

            //FormatForm();

        }

        public void LoadRecursoPartir(int EstructuraCostoItem)
        {

            try
            {



                decimal cero = 0m;
                EstructuraCostoItem ECItem =
                    DbUtil.Db.EstructuraCostoItems.Single(p => p.idInternal == EstructuraCostoItem);

                int  q = (from a in DbUtil.Db.ComparativoItems
                        where a.idEstructuraCostoItem==ECItem.idInternal
                        select a).Count();


                List<EstructuraCostoitemsingleInfo> itemList2 = new List<EstructuraCostoitemsingleInfo>();
                Session[idRecursoPartirList.Value.ToString()] = itemList2;


                if (ECItem.idAgrupadoDestino != null)
                {
                    throw new Exception(" Item no puede ser Dividido,pertenece a agrupación");
                }
                if (q>0)
                {
                  
                    throw new Exception(" Item se encuentra utilizado");
                }
                if (ECItem.idJuntoPadre != null)
                {
                    throw new Exception(" Item se encuentra agrupado");
                }


                bool recursoDividirEsPadre = (!ECItem.bitsel.Value);

                if (!ECItem.bitsel.Value)
                {
                    throw new Exception(" Item se encuentra Detallado");
                }

                
                
                if (ECItem.nivel == 2)
                {
                    throw new Exception("no se permite detallar el recurso");
                }






                RecursotoLabel.Text = ECItem.Insumo.descripcion;
                codigoLabel.Text = ECItem.Insumo.codigo;
                UnidadLabel.Text = ECItem.Insumo.InsumoUnidad.abreviacion;
                TotalDetalleLabel.Text = String.Format("{0} {1:N4}", ECItem.Moneda.simbol, cero);
                TotalRecursoLabel.Text = String.Format("{0} {1:N4}", ECItem.Moneda.simbol, ECItem.total.Value);
                simbolMoneda.Value = ECItem.Moneda.simbol;

                idEstructuraCostoPartir.Value = EstructuraCostoItem.ToString();

                BindDataItem();
            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        private void FormatForm()
        {


            idRecursoPartirList.Value = Parametros.GenerarID().ToString();


            List<EstructuraCostoitemsingleInfo> itemList2 = new List<EstructuraCostoitemsingleInfo>();
            Session[idRecursoPartirList.Value.ToString()] = itemList2;

          


        }
        private void resetEmpty()
        {
            if (itemGridView.Rows.Count == 0)
            {
                List<EstructuraCostoitemsingleInfo> itemList0 = new List<EstructuraCostoitemsingleInfo>();
                EstructuraCostoitemsingleInfo itemcero = new EstructuraCostoitemsingleInfo();
                itemcero.idInternal = 0;
                itemList0.Add(itemcero);
                itemGridView.DataSource = itemList0;
                itemGridView.DataBind();
                itemGridView.Rows[0].Visible = false;
            }

        }
        private void setEstadistica()
        {
            List<EstructuraCostoitemsingleInfo> itema =
                (List<EstructuraCostoitemsingleInfo>)Session[idRecursoPartirList.Value.ToString()];

            // TotalRecursoLabel.Text = String.Format("{0} {1:N}", simbolMonedaLabel.Value, itemb.Sum(p => p.totalReUso));
            TotalDetalleLabel.Text = String.Format("{0} {1:N4}", simbolMoneda.Value, itema.Sum(p => p.total));

        }

        #region "Nuevo Item"

        private void BindDataItem()
        {

            List<EstructuraCostoitemsingleInfo> item =
                (List<EstructuraCostoitemsingleInfo>)Session[idRecursoPartirList.Value.ToString()];


            itemGridView.DataSource = item;
            itemGridView.DataBind();
            resetEmpty(); //necesario para add

            itemGridView.FooterRow.Visible = true;

            setEstadistica();

            partirUpdatePanel.Update();



            setFooter(item);


        }

        protected void DeleteItem(object sender, EventArgs e)
        {
            try
            {

                ImageButton lnkRemove = (ImageButton)sender;
                int idInternal = int.Parse(lnkRemove.CommandArgument.ToString());

                List<EstructuraCostoitemsingleInfo> itemList =
                    (List<EstructuraCostoitemsingleInfo>)Session[idRecursoPartirList.Value.ToString()];

                EstructuraCostoitemsingleInfo drw = itemList.Single(p => p.idInternal == idInternal);

                //eliminamos de la coleccion

                itemList.Remove(drw);
                Session[idRecursoPartirList.Value.ToString()] = itemList;



                BindDataItem();


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }


        protected void EditNewItem(object sender, GridViewEditEventArgs e)
        {
            try
            {
                GridView gv = ((GridView)sender);

                gv.EditIndex = e.NewEditIndex;
                BindDataItem();
                gv.FooterRow.Visible = false;


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }
        protected void CancelNewItem(object sender, GridViewCancelEditEventArgs e)
        {
            try
            {
                GridView gv = ((GridView)sender);
                gv.EditIndex = -1;
                BindDataItem();


            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        private void setFooter(List<EstructuraCostoitemsingleInfo> recursoList)
        {
            


            Label totalBaseInsertLabel =
                                            ((Label)itemGridView.FooterRow.FindControl("totalBaseInsertLabel"));


            EstructuraCostoItem ecitem = 
                DbUtil.Db.EstructuraCostoItems.Single(p => p.idInternal == int.Parse(idEstructuraCostoPartir.Value));

            decimal subtotal = recursoList.Sum(p => p.total);
            totalBaseInsertLabel.Text = String.Format("{0} {1:N4}", simbolMoneda.Value, ecitem.total.Value - subtotal);

            

            if (recursoList.Sum(p => p.total) == ecitem.total.Value)
            {
                itemGridView.FooterRow.Visible = false;
            }

           


            // totalInsertTextBox.Text = "0";
        }



        protected void AddItem(object sender, EventArgs e)
        {
            try
            {

                List<EstructuraCostoitemsingleInfo> itemlist =
                  (List<EstructuraCostoitemsingleInfo>)Session[idRecursoPartirList.Value];

                EstructuraCostoItem ecitem =
                    DbUtil.Db.EstructuraCostoItems.Single(p => p.idInternal ==
                    int.Parse(idEstructuraCostoPartir.Value));

                string precio = ((TextBox)itemGridView.FooterRow.FindControl("precioInsertTextBox")).Text;
                string cantidad = ((TextBox)itemGridView.FooterRow.FindControl("cantidadDividirInsertTextBox")).Text;
                string codigo = ((TextBox)itemGridView.FooterRow.FindControl("codigoInsertTextBox")).Text;



                DAL.Insumo insumo = DbUtil.Db.Insumos.Single(p => p.codigo == codigo.Trim());

                if (insumo.InsumoUnidad.abreviacion.ToUpper() == "GLB")
                {
                    cantidad =  "1";
                }

                decimal total = decimal.Parse(precio) * decimal.Parse(cantidad);


                if (total > ecitem.total - itemlist.Sum(p => p.total))
                {

                    string msg = String.Format("No se permite montos superiores a: {0} {1:N} ",
                        simbolMoneda.Value, ecitem.total.Value);

                    throw new Exception(msg);
                }

                EstructuraCostoitemsingleInfo item =
                    new EstructuraCostoitemsingleInfo(Util.GenerarID(),
                        insumo.idInternal,
                        insumo.codigo,
                        insumo.descripcion,
                        insumo.InsumoUnidad.abreviacion,
                        decimal.Parse(precio),
                        decimal.Parse(cantidad),
                        total,
                        simbolMoneda.Value,
                        ecitem.idMoneda.Value);


                itemlist.Add(item);
                Session[idRecursoPartirList.Value.ToString()] = itemlist;
                BindDataItem();

            }
            catch (SqlException sqlex)
            {
                WebServerSideSqlError.Log(sqlex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + sqlex.Message.Replace("'", "") + "');", true);


            }
            catch (Exception ex)
            {
                WebServerSideError.Log(ex);
                ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UserControl),
                 "uniqueKey" + DateTime.Now, "alert('" + ex.Message.Replace("'", "") + "');", true);

            }

        }

        #endregion




    }
}